"""系统配置管理"""

import json
from pathlib import Path
from typing import Dict, Any, Optional


class SystemConfig:
    """系统配置类"""
    
    def __init__(self, config_path: Optional[Path] = None):
        self.config_path = config_path or Path.home() / ".video-transcoder" / "config.json"
        self.config_path.parent.mkdir(parents=True, exist_ok=True)
        self._config: Dict[str, Any] = self._load_default_config()
        self.load()
    
    def _load_default_config(self) -> Dict[str, Any]:
        """加载默认配置"""
        return {
            "general": {
                "language": "zh_CN",
                "theme": "default",
                "auto_start": False,
                "check_updates": True,
            },
            "encoding": {
                "default_format": "mp4",
                "quality_preset": "medium",
                "thread_count": 0,  # 0表示自动检测
                "gpu_acceleration": True,
                "hardware_encoder": "auto",
            },
            "monitoring": {
                "refresh_rate": 60,  # Hz
                "show_temperatures": True,
                "show_usage": True,
                "alert_threshold": 90,  # %
                "log_level": "INFO",
            },
            "paths": {
                "input_directory": str(Path.home() / "Videos"),
                "output_directory": str(Path.home() / "Videos" / "Transcoded"),
                "temp_directory": str(Path.home() / ".video-transcoder" / "temp"),
            },
            "gpu": {
                "preferred_gpu": "auto",
                "max_gpu_usage": 80,  # %
                "temperature_limit": 85,  # °C
                "memory_threshold": 90,  # %
            }
        }
    
    def load(self) -> bool:
        """从文件加载配置"""
        try:
            if self.config_path.exists():
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    self._merge_config(loaded_config)
                return True
        except Exception as e:
            print(f"加载配置失败: {e}")
        return False
    
    def save(self) -> bool:
        """保存配置到文件"""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, indent=2, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False
    
    def _merge_config(self, new_config: Dict[str, Any]) -> None:
        """合并配置"""
        def merge_dict(base: Dict[str, Any], update: Dict[str, Any]) -> None:
            for key, value in update.items():
                if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                    merge_dict(base[key], value)
                else:
                    base[key] = value
        
        merge_dict(self._config, new_config)
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        config = self._config
        
        for k in keys:
            if isinstance(config, dict) and k in config:
                config = config[k]
            else:
                return default
        
        return config
    
    def set(self, key: str, value: Any) -> None:
        """设置配置值"""
        keys = key.split('.')
        config = self._config
        
        for k in keys[:-1]:
            if k not in config or not isinstance(config[k], dict):
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    @property
    def data(self) -> Dict[str, Any]:
        """获取完整配置数据"""
        return self._config.copy()


# 全局配置实例
_config_instance: Optional[SystemConfig] = None


def get_config() -> SystemConfig:
    """获取全局配置实例"""
    global _config_instance
    if _config_instance is None:
        _config_instance = SystemConfig()
    return _config_instance